package com.mdd.maduoduo.activity;

import android.content.Intent;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mdd.maduoduo.R;
import com.mdd.maduoduo.constants.CommonConstants;
import com.mdd.maduoduo.di.component.DaggerUIComponent;
import com.mdd.maduoduo.di.component.UIComponent;
import com.mdd.maduoduo.entity.LoginEntity;
import com.mdd.maduoduo.entity.Response;
import com.mdd.maduoduo.event.WxLoginEvent;
import com.mdd.maduoduo.presenter.LoginPresenter;
import com.mdd.maduoduo.utils.RxBus;
import com.mdd.maduoduo.utils.SpUtils;
import com.mdd.maduoduo.utils.ToastUtils;
import com.mdd.maduoduo.utils.Utils;
import com.mdd.maduoduo.view.interfaces.LoginView;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;

public class LoginActivity extends BaseActivity implements LoginView {

    private TextView tvRule;

    private RelativeLayout rlWxLogin;

    private CheckBox checkbox;

    // IWXAPI 是第三方app和微信通信的openApi接口
    private IWXAPI api;

    @Inject
    public LoginPresenter mPresenter;

    private CompositeDisposable disposables = new CompositeDisposable();

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        super.initView();
        next();
        api = WXAPIFactory.createWXAPI(this, CommonConstants.WX_APPID, true);
        tvRule = findViewById(R.id.tvRule);
        rlWxLogin = findViewById(R.id.rlWxLogin);
        checkbox = findViewById(R.id.checkbox);
        setTextContent();

        disposables.add(
                RxBus.getInstance().toObservable(WxLoginEvent.class)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(event -> {
                            String url = CommonConstants.API_PRODUCT_URL+"/olda-play-auth/oauth/token?grant_type=mggAppWechatGrant&mggWechatAuthCode=" + event.code;
                            mPresenter.login(LoginActivity.this,url);
                        })
        );
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.onDestroy();
    }

    @Override
    protected void initializeInjector() {
        super.initializeInjector();
        mPresenter = new LoginPresenter();
        UIComponent uiComponent = DaggerUIComponent.builder().applicationComponent(getApplicationComponent())
                .activityModule(getActivityModule()).build();
        uiComponent.inject(this);
        mPresenter.setLoginView(this);
    }

    @Override
    protected void onClick() {
        rlWxLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (checkbox.isChecked()) {
                    if (Utils.isFastClick()) {
                        wxLgoin();

                    }
                } else {
                    ToastUtils.showLongToast(LoginActivity.this, "请阅读并同意《用户协议》和《隐私政策》");
                }


            }
        });
    }

    private void wxLgoin() {
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo"; // 只能填 snsapi_userinfo
        req.state = "weixin_login";
        api.sendReq(req);
    }

    private void setTextContent() {
        String rule = "登录即表示您同意《用户协议》和《隐私政策》";
        if (rule.contains("《")) {
            SpannableString spannableString = new SpannableString(rule);

            spannableString.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    Intent intent = new Intent(LoginActivity.this,WebViewActivity.class);
                    intent.putExtra("title","用户协议");
                    intent.putExtra("url",CommonConstants.USER_RULE);
                    startActivity(intent);
                }
            }, 8, 14, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            spannableString.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    Intent intent = new Intent(LoginActivity.this,WebViewActivity.class);
                    intent.putExtra("title","隐私政策");
                    intent.putExtra("url",CommonConstants.Privacy);
                    startActivity(intent);
                }
            }, 15, rule.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);


            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#007AFF")),
                    8, 14, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#007AFF")),
                    15, rule.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            tvRule.setText(spannableString);
            tvRule.setMovementMethod(LinkMovementMethod.getInstance());
        }
    }

    @Override
    public void renderSuccess(Response<LoginEntity> response) {
        //保存token
        SpUtils.put(LoginActivity.this, CommonConstants.TOKEN, response.data.access_token);
        startActivity(new Intent(LoginActivity.this, MainActivity.class));
        finish();
    }

    private void next() {
        String token = SpUtils.get(LoginActivity.this, CommonConstants.TOKEN);
        if (!token.isEmpty()) {
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        }
    }
}
